# -*- coding: utf-8 -*-
# Copyright © 2024 weidongkl <weidongkx@gmail.com>
import logging
import os
from excavator.utils.output import ExcavatorJobOutput
from excavator.job.base import Job
from excavator.models.report import notify_err, notify_info
from excavator.group import BootGroup
from excavator.models.pkg import DnfUpgrade

logger = logging.getLogger("excavator.job")


class BootDbus(Job):
    group = BootGroup
    requires = (DnfUpgrade,)
    provides = ()

    def run(self, *args, **kwargs):
        ExcavatorJobOutput.info(self.name, "process dbus.service")
        dbus_broker_svc = "/usr/lib/systemd/system/dbus-broker.service"
        dbus_svc = "/etc/systemd/system/dbus.service"

        if not os.path.exists(dbus_svc):
            if os.path.exists(dbus_broker_svc):
                if os.path.islink(dbus_svc):
                    # 无效链接需要删除，防止影响后面的链接
                    logger.info("remove unused dbus.service link")
                    os.remove(dbus_svc)
                os.symlink(dbus_broker_svc, dbus_svc)
                msg = "create dbus.service link success"
                logger.info(msg)
                notify_info(msg, self.name)
                return
            else:
                msg = "dbus service({}) not exists".format(dbus_broker_svc)
                logger.error(msg)
                notify_err(msg, self.name)
                return
        notify_info("skip link dbus service", self.name)
